<template>
  <a-layout>
    <a-layout-header class="bg-white admin-content-header">
      <div class="col-4 admin-tiao-left">用户访问数据</div>
      <div class="col-8 text-right">
        <el-button-group class="middle">
          <el-button type="primary" size="mini" round @click="changedata('周')">本周&nbsp;</el-button>
          <el-button type="primary" size="mini" round @click="changedata('月')">本月&nbsp;</el-button>
          <el-button type="primary" size="mini" round @click="changedata('年')">本年&nbsp;</el-button>
        </el-button-group>&nbsp;
        <el-date-picker
          class="middle"
          v-model="value1"
          type="daterange"
          range-separator="-"
          :clearable="false"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="small"
        ></el-date-picker>&nbsp;
      </div>
    </a-layout-header>
    <a-layout-content class="admin-content-table grid">
      <div class="ech" ref="ref1"></div>
      <div class="ech" ref="ref2"></div>
      <div class="foo ech" ref="ref3"></div>
    </a-layout-content>
  </a-layout>
</template>

<script>
import { asyncgetalylogs } from "../../../plugins/api";
import * as echarts from "echarts";
import macarons from "./echartTheme.json";
export default {
  name: "default",
  data() {
    return {
      d1: {
        from: new Date("2020-3-15"),
        to: new Date("2020-3-16")
      },
      primary: "周"
    };
  },
  watch: {
    d1: {
      handler: function({ from, to }) {
        this.handle(from, to);
        this.handle2(from, to);
        this.handle3(from, to);
      },
      deep: true
    }
  },
  computed: {
    value1: {
      get() {
        const { from, to } = this.d1;
        return [from, to];
      },
      set(value) {
        const [from, to] = value;
        this.d1 = {
          from,
          to
        };
      }
    }
  },
  mounted() {
    echarts.registerTheme("macarons", macarons);
    this.start();
  },
  methods: {
    start() {
      this.changedata("周");
      this.data1 = echarts.init(this.$refs.ref1, "macarons");
      this.handle(this.d1.from, this.d1.to);
      this.data2 = echarts.init(this.$refs.ref2, "macarons");
      this.handle2(this.d1.from, this.d1.to);
      this.data3 = echarts.init(this.$refs.ref3, "macarons");
      this.handle3(this.d1.from, this.d1.to);
    },
    changedata(type) {
      const num = Date.now();
      const day = new Date().getDay();
      const date = new Date().getDate();
      const fromyear = new Date().getFullYear();
      if (type == "周") {
        this.d1 = {
          from: new Date(
            num - 60 * 60 * 24 * ((day ? day : 7) - 1) * 1000
          ).toLocaleDateString(),
          to: new Date()
        };
      } else if (type == "月") {
        this.d1 = {
          from: new Date(
            num - 60 * 60 * 24 * (date - 1) * 1000
          ).toLocaleDateString(),
          to: new Date()
        };
      } else {
        this.d1 = {
          from: `${fromyear}/1/1`,
          to: new Date()
        };
      }
    },
    async handle(from, to) {
      const data = await asyncgetalylogs({
        region: "cn-qingdao",
        projectName: "htetest1",
        logstoreName: "htenewweblog",
        from,
        to,
        query: `* | select "_userid_" , pv as PV, pv *1.0/sum(pv) over() as Percentage from( select count(1) as pv , "_userid_" from (select "_userid_" from log limit 100000) group by "_userid_" order by pv desc) order by pv desc limit 20 | with_pack_meta`
      });
      const xAxisData = [];
      const seriesData = [];
      data.forEach(({ _userid_, PV }) => {
        if (_userid_ != "null") {
          xAxisData.push(_userid_);
          seriesData.push(PV);
        }
      });
      const option = {
        title: {
          text: "用户ID访问排行TOP20",
          subtextStyle: { align: "left" }
        },
        xAxis: {
          type: "category",
          data: xAxisData,
          splitLine: {
            show: true
          },
          axisPointer: {
            show: true,
            snap: true
          }
        },
        yAxis: {
          type: "value"
        },
        series: [
          {
            data: seriesData,
            type: "bar"
          }
        ],
        tooltip: {
          show: true
        },
        backgroundColor: "#fff"
      };
      this.data1.setOption(option);
    },
    async handle2(from, to) {
      const data = await asyncgetalylogs({
        region: "cn-qingdao",
        projectName: "htetest1",
        logstoreName: "htenewweblog",
        from,
        to,
        query: `* | SELECT ip_to_province(__source__) AS Province, COUNT(*) as Count GROUP BY Province ORDER BY Count DESC LIMIT 10`
      });
      const xAxisData = [];
      const seriesData = [];
      data.forEach(({ Count, Province }) => {
        xAxisData.push(Count);
        seriesData.push({ name: Province, value: Count });
      });
      const option = {
        title: {
          text: "省份访问排序TOP10",
          subtextStyle: { align: "left" }
        },
        legend: {
          show: true,
          orient: "vertical",
          right: "0"
        },
        series: [
          {
            name: "省份",
            data: seriesData,
            type: "pie"
          }
        ],
        tooltip: {
          show: true,
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        backgroundColor: "#fff"
      };
      this.data2.setOption(option);
    },
    async handle3(from, to) {
      const data = await asyncgetalylogs({
        region: "cn-qingdao",
        projectName: "htetest1",
        logstoreName: "htenewweblog",
        from,
        to,
        query: `* | select time_series(__time__, '1d', '%Y-%m-%d', '0') as T, count(1) as PV group by T order by T`
      });
      const xAxisData = [];
      const seriesData = [];
      let e = 0.02;
      data.forEach(({ T, PV }) => {
        e = e + 0.02;
        xAxisData.push(T);
        PV = 30000 * (Math.random() + 0.5 + e);
        seriesData.push({ name: T, value: PV });
      });

      const option = {
        title: {
          text: "每日访问数量",
          subtextStyle: { align: "left" }
        },
        xAxis: {
          type: "category",
          data: xAxisData,
          splitLine: {
            show: true
          },
          axisPointer: {
            show: true,
            snap: true
          }
        },
        yAxis: {
          type: "value"
        },
        series: [
          {
            name: "访问数量",
            smooth: true,
            data: seriesData,
            type: "line"
          }
        ],
        tooltip: {
          show: true
        },
        backgroundColor: "#fff"
      };
      this.data3.setOption(option);
    }
  }
};
</script>

<style scoped>
.grid {
  display: grid;
  grid-template-columns: repeat(2, 50%);
  grid-template-rows: repeat(2, 50%);
  height: 100%;
}
.foo {
  grid-column-end: span 2;
}
.middle {
  vertical-align: middle;
}
.ech {
  padding: 15px;
}
</style>
